package com.davy.gridpoint.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.davy.gridpoint.BaseActivity;
import com.davy.gridpoint.R;
import com.davy.gridpoint.adapter.LineAdapter;
import com.davy.gridpoint.adapter.XbAdapter;
import com.davy.gridpoint.http.CommonHttpConsts;
import com.davy.gridpoint.http.HttpCallbackData;
import com.davy.gridpoint.http.HttpClient;
import com.davy.gridpoint.qlxj.TakeActivity;
import com.davy.gridpoint.qlxj.adapter.ImgAdapter;
import com.davy.gridpoint.utils.DeviceIdHelper;
import com.davy.gridpoint.utils.DialogUitl;
import com.davy.gridpoint.utils.ImageUtil;
import com.davy.gridpoint.utils.LogUtils;
import com.davy.gridpoint.utils.SPUtils;
import com.davy.gridpoint.utils.StringUtils;
import com.davy.gridpoint.utils.ToastUtil;
import com.davy.gridpoint.view.CustomImageView;
import com.davy.gridpoint.view.MyCountDownTimer;
import com.davy.gridpoint.view.MyRecyclerView;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;

import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.tilesource.XYTileSource;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.Overlay;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GridActivity extends BaseActivity {
    private final int REQUEST_IMG = 1001;
    private final int REQUEST_CODE_CAPTURE = 1002;
    private EditText etMileage1, etMileage2;
    private TextView tvTitle, tvLocation, tvLine;
    private AppCompatButton btnConfirm;
    private MyRecyclerView recyclerImg;
    private ImgAdapter imgAdapter;
    private ArrayList<Map> imgList;
    //    private RecyclerView recyclerLine;
//    private LineAdapter lineAdapter;
    private ArrayList<Map> lineList;
    private ArrayList<String> xbList;
    private RecyclerView recyclerXb;
    private XbAdapter xbAdapter;
    private MapView mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid);
        Configuration.getInstance().setTileFileSystemCacheMaxBytes(1024 * 1024 * 512); // 512MB
        Configuration.getInstance().setTileDownloadThreads((short) 4); // 并行下载线程数
//        // 重要初始化
//        Configuration.getInstance().setUserAgentValue(getPackageName());
//        // 在应用启动时设置缓存大小（单位MB）
//        Configuration.getInstance().setOsmdroidBasePath(new File(getCacheDir(), "osmdroid"));
//        Configuration.getInstance().setOsmdroidTileCache(new File(getCacheDir(), "tiles"));
//        Configuration.getInstance().setTileFileSystemCacheMaxBytes(1024 * 1024 * 512); // 512MB缓存
//        // 在应用初始化时设置
//        Configuration.getInstance().setTileDownloadThreads((short) 8); // 默认2，可增加到4-8
//        Configuration.getInstance().setTileFileSystemThreads((short) 8);
        xbList = new ArrayList<>();
        imgList = new ArrayList<>();
        lineList = new ArrayList<>();
        decimalFormat = new DecimalFormat("#.00000000");
        decimalFormat1 = new DecimalFormat("#.00");
        statusbar4();
        initView();
    }

    protected DecimalFormat decimalFormat;
    protected DecimalFormat decimalFormat1;
    private String mLongitude, mLatitude, mAltitude;
    public MyCountDownTimer myCountDownTimer;
    private String inXb = "";
    private String strSelect = "";
    private String pwsSelect = "";
    private String lineId = "";
    private String lineName = "";
    private String filePath = "";

    private void initView() {
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("里程打卡");
        recyclerImg = findViewById(R.id.recyclerImg);
        btnConfirm = findViewById(R.id.btnConfirm);
        etMileage1 = findViewById(R.id.etMileage1);
        etMileage2 = findViewById(R.id.etMileage2);
        tvLocation = findViewById(R.id.tvLocation);
        mapView = findViewById(R.id.mapView);
//        recyclerLine = findViewById(R.id.recyclerLine);
        tvLine = findViewById(R.id.tvLine);
        // 设置Flexbox布局管理器
//        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
//        layoutManager.setFlexDirection(FlexDirection.ROW); // 主轴方向为水平
//        layoutManager.setFlexWrap(FlexWrap.WRAP); // 自动换行
//        layoutManager.setJustifyContent(JustifyContent.FLEX_START); // 左对齐
//        recyclerLine.setLayoutManager(layoutManager);
//        lineAdapter = new LineAdapter(mContext, lineList);
//        recyclerLine.setAdapter(lineAdapter);
//        lineAdapter.setItemClickListener((position, map) -> {
//            lineId = map.get("LineId") + "";
//            lineName = map.get("LineName") + "";
//            lineAdapter.setPop(position);
//        });

        xbList.add("上行");
        xbList.add("下行");
        xbList.add("单线");
        xbList.add("双线");

        findViewById(R.id.imgBack).setOnClickListener(v -> finish());
        recyclerXb = findViewById(R.id.recyclerXb);
        recyclerXb.setLayoutManager(new GridLayoutManager(mContext, 4, RecyclerView.VERTICAL, false));
        xbAdapter = new XbAdapter(mContext, xbList);
        recyclerXb.setAdapter(xbAdapter);
        xbAdapter.setItemClickListener((position, map) -> {
            inXb = map;
            xbAdapter.setPop(position);
        });

        strSelect = SPUtils.get(mContext, "strSelect", "") + "";
        pwsSelect = SPUtils.get(mContext, "pwsSelect", "") + "";
        if (!StringUtils.isEmpty(strSelect)) {
            GetPwsLine();
        }

        findViewById(R.id.relaLayout).setOnClickListener(v -> {
            StringUtils.hintKeyBoard(mContext, etMileage1);
        });
        findViewById(R.id.imgDw).setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }

            if (!StringUtils.isEmpty(MainActivity.mLongitude)) {
                mLongitude = MainActivity.mLongitude;
                mLatitude = MainActivity.mLatitude;
                mAltitude = MainActivity.mAltitude;
                tvLocation.setText("经度：" + mLongitude + "  纬度" + mLatitude);

                double aLatitude = Double.valueOf(mLatitude);
                double aLongitude = Double.valueOf(mLongitude);
                // 设置初始位置
                GeoPoint startPoint = new GeoPoint(aLatitude, aLongitude);
                mapView.getController().setCenter(startPoint);
                mapView.getController().setZoom(18.0);
                refreshMarkers(startPoint);
            }
        });
        recyclerImg.setLayoutManager(new LinearLayoutManager(mContext));
//        recyclerImg.setLayoutManager(new GridLayoutManager(mContext, 3, RecyclerView.VERTICAL, false));
        imgAdapter = new ImgAdapter(mContext, imgList);
        recyclerImg.setAdapter(imgAdapter);
        imgAdapter.setItemClickListener(new ImgAdapter.ItemClickListener() {
            @Override
            public void addClick(int position) {
                if (StringUtils.isFastClick()) {
                    return;
                }
                File appDir = new File(Environment.getExternalStorageDirectory(), "Davy");
                if (!appDir.exists()) {
                    appDir.mkdir();
                }
                //图片文件名称
                String fileName = "grid_" + System.currentTimeMillis() + ".jpeg";
                File file = new File(appDir, fileName);
                filePath = file.getAbsolutePath();

                Uri photoURI = FileProvider.getUriForFile(mContext, "com.davy.gridpoint.fileprovider", file);
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMG);
//                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//                    startActivityForResult(takePictureIntent, REQUEST_CODE_CAPTURE);
//                }
            }

            @Override
            public void delClick(int position, Map mList) {
                if (StringUtils.isFastClick()) {
                    return;
                }

                delDialog(position);
            }

            @Override
            public void getClick(int position, Map mList) {
                if (StringUtils.isFastClick()) {
                    return;
                }
                String img = mList.get("img") + "";
                Double isBt = 1.0; //1：保存 2：提交
                if (mList.containsKey("isBt")) {
                    isBt = Double.valueOf(mList.get("isBt") + "");
                }

                if (isBt.intValue() == 2) {
                    if (!img.startsWith("http")) {
                        img = HttpClient.imgUrl + img.replace("/storage/emulated/0/Davy/", "");
                    }
                }

                imgDialog(img);
            }
        });

        btnConfirm.setOnClickListener(v -> {
            if (StringUtils.isEmpty(lineName)) {
                ToastUtil.showNew(mContext, "请选择线路！");
                return;
            }
            if (StringUtils.isEmpty(inXb)) {
                ToastUtil.showNew(mContext, "请选择行别！");
                return;
            }
            String mileage1 = etMileage1.getText().toString().trim();
            String mileage2 = etMileage2.getText().toString().trim();
            if (StringUtils.isEmpty(mileage1) || StringUtils.isEmpty(mileage2)) {
                ToastUtil.showNew(mContext, "请输入里程信息");
                return;
            }

            if (imgList.isEmpty()) {
                ToastUtil.showNew(mContext, "请添加图片！");
                return;
            }
            if (StringUtils.isEmpty(mLongitude)) {
                ToastUtil.showNew(mContext, "GPS定位中，请稍等！");
                return;
            }
            if (StringUtils.isFastClick()) {
                return;
            }
            List<String> fileName = new ArrayList<>();
            List<File> files = new ArrayList<>();
            int i = 0;
            while (imgList.size() > i) {
                File file = new File(imgList.get(i).get("img").toString().trim());
                if (file.isFile()) {
                    files.add(file);
                    fileName.add(file.getName());
//                    try {
//                        file = smartCompressImage(mContext, imgList.get(i).get("img").toString().trim(), 1024 * 3);
//                        files.add(file);
//                        fileName.add(file.getName());
//                    } catch (IOException e) {
//                        throw new RuntimeException(e);
//                    }
                }
                i++;
            }

            Map<String, Object> gridMap = new HashMap<>();
            gridMap.put("pws_id", pwsSelect);
            gridMap.put("pws_name", strSelect);
            gridMap.put("line_id", lineId);
            gridMap.put("line_name", lineName);
            gridMap.put("imei", DeviceIdHelper.getDeviceId(mContext));
            gridMap.put("geo_end_milege", mileage2 + "");
            gridMap.put("geo_start_milege", mileage1 + "");
            gridMap.put("xb", inXb);
            gridMap.put("type", "");
            gridMap.put("longitude", mLongitude);
            gridMap.put("latitude", mLatitude);
            gridMap.put("altitude", mAltitude);
            //gridMap.put("img_path", fileName);

            FreedomPoint(gridMap, fileName, files);
        });

        myCountDownTimer = new MyCountDownTimer(1500, 1000);
        myCountDownTimer.setTimeCallback(() -> {
            myCountDownTimer.cancel();
            if (!StringUtils.isEmpty(MainActivity.mLongitude)) {
                mLongitude = MainActivity.mLongitude;
                mLatitude = MainActivity.mLatitude;
                mAltitude = MainActivity.mAltitude;
                tvLocation.setText("经度：" + mLongitude + "  纬度" + mLatitude);

                double aLatitude = Double.valueOf(mLatitude);
                double aLongitude = Double.valueOf(mLongitude);
                // 设置初始位置
                GeoPoint startPoint = new GeoPoint(aLatitude, aLongitude);
                mapView.getController().setCenter(startPoint);
                mapView.getController().setZoom(18.0);
                refreshMarkers(startPoint);
            } else {
//                tvLocation.setText("");
                myCountDownTimer.start();
            }
        });

        myCountDownTimer.start();

        findViewById(R.id.tvLock).setOnClickListener(v -> {
            if (StringUtils.isEmpty(mLongitude)) {
                ToastUtil.showNew(mContext, "GPS定位中，请稍等！");
                return;
            }
            if (StringUtils.isFastClick()) {
                return;
            }
            startActivity(new Intent(mContext, MapActivity.class));
        });

        //清理缓存并重新加载瓦片
//        mapView.getTileProvider().clearTileCache();
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                // 1. 禁用自动 DPI 缩放
                mapView.setTilesScaledToDpi(false);
                // 2. 根据屏幕密度手动设置图块尺寸
                final float scale = getResources().getDisplayMetrics().density;
                LogUtils.e("TAG", "scale:" + scale);
                final int tileSize = (int) (256 * scale); // 在hdpi上约为384, xhdpi上为512
                LogUtils.e("TAG", "tileSize:" + tileSize);
                // 在 MapView 初始化时设置镜像源
                // "https://rt0.map.gtimg.com/realtimerender/", //集成腾讯/高德地图
                // "https://a.tile.openstreetmap.org/",  // 备用国际源（部分可访问）
                mapView.setTileSource(new XYTileSource("OSM_Mirror",  // 自定义名称
                        4, 22, 760, ".png", new String[]{"https://tile.openstreetmap.de/", // 德国镜像
                        "https://tile.openstreetmap.jp/" // 日本镜像（推荐）
                }));

                mapView.setUseDataConnection(true);
                mapView.setMinZoomLevel(4.0); // 设置最小缩放级别
                mapView.setMaxZoomLevel(22.0); // 支持更高缩放级别
                // 设置初始地图位置
                mapController = mapView.getController();
                mapController.setZoom(18.0);
                // 启用交互控件
                mapView.setBuiltInZoomControls(true);
                mapView.setMultiTouchControls(true); // 启用多指缩放

                GeoPoint startPoint = new GeoPoint(39.9242, 116.4274); // 北京坐标
                mapController.setCenter(startPoint);

                // 添加点击监听器
                mapView.getOverlays().add(new MapEventsOverlay(new MapEventsReceiver() {
                    @Override
                    public boolean singleTapConfirmedHelper(GeoPoint point) {
                        handleMapClick(point); // 处理点击事件
                        return true;
                    }

                    @Override
                    public boolean longPressHelper(GeoPoint point) {
                        return false;
                    }
                }));
            }
        });
        findViewById(R.id.lineLayout).setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }

            if (lineList.size() > 0) {
                lineDialog();
            } else {
                ToastUtil.showNew(mContext, "未获取到线路数据！");
            }
        });
    }

    public void delDialog(int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_exit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvSave = v.findViewById(R.id.tvSave);
        TextView tvName = v.findViewById(R.id.tvName);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());
        tvName.setText("确认删除该图片吗");
        tvSave.setOnClickListener(view -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            imgList.remove(id);
            imgAdapter.setData(imgList);
            dialog.dismiss();
        });
    }

    public File smartCompressImage(Context context, String imageUri, int maxSizeKB) throws IOException {
        // 1. 文件路径
        if (imageUri == null) return null;

        // 2. 读取图片信息
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imageUri, options);

        // 3. 计算目标尺寸（保持宽高比）
        int targetWidth = 1080; // 根据需求调整
        int targetHeight = (int) (options.outHeight * ((float) targetWidth / options.outWidth));

        // 4. 尺寸压缩
        options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(imageUri, options);

        // 5. 处理旋转
        bitmap = correctImageRotation(bitmap, imageUri);

        // 6. 质量压缩（动态调整质量）
        File outputFile = new File(context.getCacheDir(), "upload_" + System.currentTimeMillis() + ".jpeg");
        if (outputFile.length() / 1024 > 2048) {
            int quality = 90;
            do {
                try (FileOutputStream out = new FileOutputStream(outputFile)) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
                }
                quality -= 10;
            } while (outputFile.length() / 1024 > maxSizeKB && quality > 30);
        }

        if (!bitmap.isRecycled()) {
            bitmap.recycle();
        }

        return outputFile;
    }

    private Bitmap correctImageRotation(Bitmap bitmap, String imagePath) throws IOException {
        ExifInterface exif = new ExifInterface(imagePath);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                matrix.postRotate(90);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.postRotate(180);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                matrix.postRotate(270);
                break;
            default:
                return bitmap;
        }

        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public File compressBySize(File srcFile, int maxWidth, int maxHeight) throws IOException {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(srcFile.getAbsolutePath(), options);

        options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
        options.inJustDecodeBounds = false;

        Bitmap scaledBitmap = BitmapFactory.decodeFile(srcFile.getAbsolutePath(), options);
        File outputFile = new File(srcFile.getParent(), "scaled_" + srcFile.getName());

        try (FileOutputStream out = new FileOutputStream(outputFile)) {
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);
        }

        if (!scaledBitmap.isRecycled()) {
            scaledBitmap.recycle();
        }

        return outputFile;
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    private String lineName1 = "";
    private String lineId1 = "";

    public void lineDialog() {
        lineName1 = lineName;
        lineId1 = lineId;
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        android.app.AlertDialog dialog = builder.create();
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_line, null);
        TextView tvClose = v.findViewById(R.id.tvClose);
        TextView tvSave = v.findViewById(R.id.tvSave);
        RecyclerView recyclerLine = v.findViewById(R.id.recyclerLine);
        // 设置Flexbox布局管理器
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        layoutManager.setFlexDirection(FlexDirection.ROW); // 主轴方向为水平
        layoutManager.setFlexWrap(FlexWrap.WRAP); // 自动换行
        layoutManager.setJustifyContent(JustifyContent.FLEX_START); // 左对齐
        recyclerLine.setLayoutManager(layoutManager);
        LineAdapter lineAdapter1 = new LineAdapter(mContext, lineList);
        recyclerLine.setAdapter(lineAdapter1);
        lineAdapter1.setItemClickListener((position, map) -> {
            lineId1 = map.get("LineId") + "";
            lineName1 = map.get("LineName") + "";
            lineAdapter1.setPop(position);
        });


        for (int i = 0; i < lineList.size(); i++) {
            String LineName = lineList.get(i).get("LineName") + "";
            if (LineName.equals(lineName)) {
                lineAdapter1.setPop(i);
                break;
            }
        }

        dialog.setCanceledOnTouchOutside(true);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvClose.setOnClickListener(v1 -> dialog.dismiss());
        tvSave.setOnClickListener(v2 -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            if (StringUtils.isEmpty(lineName1)) {
                ToastUtil.showNew(mContext, "请选择线路！");
                return;
            }
            lineId = lineId1;
            lineName = lineName1;
            tvLine.setText(lineName);
            dialog.dismiss();
        });
    }

    private void FreedomPoint(Map gridMap, List<String> fileName, List<File> files) {
        String json = new Gson().toJson(gridMap);
        LogUtils.e("TAG", "json:" + json);
        LogUtils.e("TAG", "fileName:" + fileName.toString());

        HttpClient.getInstance().postData(CommonHttpConsts.FreedomPoint, "FreedomPoint").params("json", json).addUrlParams("file_name", fileName).addFileParams("file", files).execute(new HttpCallbackData() {

            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                ToastUtil.showNew(mContext, msg);
                if (code == 200) {
                    finish();
                }
            }

            @Override
            public void onError() {
                super.onError();
                ToastUtil.showNew(mContext, StringUtils.error_context);
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }
        });
    }

    private void GetPwsLine() {
        HttpClient.getInstance().getData(CommonHttpConsts.GetPwsLine, "GetPwsLine").tag(this).params("pwsid", pwsSelect).execute(new HttpCallbackData() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);

                if (code == 200) {
                    if (!StringUtils.isEmpty(info)) {
                        String string = StringUtils.decompressForGzip(info);
                        LogUtils.e("TAG", "string:" + string);
                        lineList = (ArrayList<Map>) JSONArray.parseArray(string, Map.class);
//                        if (lineList.size() > 0) {
//                            lineAdapter.setData(lineList);
//                        }
                    }
                } else {
                    ToastUtil.show(msg);
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }

            @Override
            public void onError() {
                super.onError();
                ToastUtil.show(StringUtils.error_context);
            }
        });
    }

    public void imgDialog(String milepostStr) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        android.app.AlertDialog dialog = builder.create();
        // 显示对话框前，设置全屏
        dialog.setOnShowListener(d -> {
            // 获取对话框窗口
            Window window = dialog.getWindow();
            if (window != null) {
                // 设置窗口的属性以全屏显示
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                window.setBackgroundDrawableResource(android.R.color.transparent);
            }
        });

        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_img_item, null);
        ImageView tvClose = v.findViewById(R.id.tvClose);
        CustomImageView imgYu1 = v.findViewById(R.id.imgYu1);
        dialog.setCanceledOnTouchOutside(true);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);

        Glide.with(mContext).load(milepostStr).error(R.mipmap.icon_error).into(imgYu1);

        tvClose.setOnClickListener(v1 -> dialog.dismiss());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_IMG) {
//                Bundle extras = data.getExtras();
//                Uri imgUri = data.getData();
                //LogUtils.e("TAG", "extras:" + data.toString());

                fileSy(filePath);

//                Map dataMap = new HashMap();
//                dataMap.put("isBt", 1);//1：未提交 2：提交
//                dataMap.put("p_time", StringUtils.getTimeS());
//                dataMap.put("img", filePath);//extras.get("data")
//                dataMap.put("type", 1);
//                imgList.add(dataMap);
//                imgAdapter.setData(imgList);
            }
            if (requestCode == REQUEST_CODE_CAPTURE) {
                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                // 使用Bitmap imageBitmap做你想做的事情，例如显示在ImageView中
//                imageView.setImageBitmap(imageBitmap);
                if (imageBitmap != null) {
                    String path = saveImage(mContext, imageBitmap);
                    LogUtils.e("TAG", "path:" + path);
                    Map dataMap = new HashMap();
                    dataMap.put("isBt", 1);//1：未提交 2：提交
                    dataMap.put("img", path);
                    dataMap.put("type", 1);
                    imgList.add(dataMap);
                    imgAdapter.setData(imgList);
                }
            }
        }
    }

    //添加水印
    public void fileSy(String imageUri) {
        // 1. 文件路径
        if (imageUri == null) return;

        // 2. 读取图片信息
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imageUri, options);

        // 3. 计算目标尺寸（保持宽高比）
        int targetWidth = 1080; // 根据需求调整
        int targetHeight = (int) (options.outHeight * ((float) targetWidth / options.outWidth));

        // 4. 尺寸压缩
        options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(imageUri, options);

        // 5. 处理旋转
        try {
            bitmap = correctImageRotation(bitmap, imageUri);

            // 6. 质量压缩（动态调整质量）
            File outputFile = new File(filePath);
            if (outputFile.length() / 1024 > 2048) {
                int quality = 90;
                do {
                    try (FileOutputStream out = new FileOutputStream(outputFile)) {
                        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
                    }
                    quality -= 10;
                } while (outputFile.length() / 1024 > 3072 && quality > 30);
            }

            bitmap = ImageUtil.drawTextToLeftTop(mContext, bitmap, StringUtils.getTimeS() + "", 30, R.color.black, 10, 18);
            if (!StringUtils.isEmpty(mLongitude)) {
                bitmap = ImageUtil.drawTextToLeftTop(mContext, bitmap, "经度:" + mLongitude, 28, R.color.black, 10, 50);
                bitmap = ImageUtil.drawTextToLeftTop(mContext, bitmap, "纬度:" + mLatitude, 28, R.color.black, 10, 82);
            }

            FileOutputStream fos = new FileOutputStream(outputFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }
            // 其次把文件插入到系统图库
            String path = outputFile.getAbsolutePath();
            // 最后通知图库更新
            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));

            if (!StringUtils.isEmpty(path)) {
                Map dataMap = new HashMap();
                dataMap.put("isBt", 1);//1：未提交 2：提交
                dataMap.put("p_time", StringUtils.getTimeS());
                dataMap.put("img", path);
                dataMap.put("type", 1);
                imgList.add(dataMap);
                imgAdapter.setData(imgList);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            e.printStackTrace();
        }


//        LogUtils.e("TAG", "imageUri:" + imageUri);
//        Bitmap mBitmap = BitmapFactory.decodeFile(imageUri);
//        LogUtils.e("TAG", "mBitmap:" + mBitmap);
//        if (mBitmap != null) {
//            Bitmap mp = ImageUtil.drawTextToLeftTop(mContext, mBitmap,
//                    StringUtils.getTimeS() + "", 30, R.color.black, 10, 18);
//            if (!StringUtils.isEmpty(mLongitude)) {
//                mp = ImageUtil.drawTextToLeftTop(mContext, mp,
//                        "经纬度：" + mLongitude + "  " + mLatitude, 30, R.color.black, 10, 50);
//            }
//
//            String path = saveImage(mContext, mp);
//            LogUtils.e("TAG", "path:" + path);
//            if (!StringUtils.isEmpty(path)) {
//                Map dataMap = new HashMap();
//                dataMap.put("isBt", 1);//1：未提交 2：提交
//                dataMap.put("p_time", StringUtils.getTimeS());
//                dataMap.put("img", path);
//                dataMap.put("type", 1);
//                imgList.add(dataMap);
//                imgAdapter.setData(imgList);
//            }
//        }
    }

    //保存图片
    public String saveImage(Context context, Bitmap bmp) {
        // 首先保存图片 创建文件夹
        LogUtils.e("TAG", "----" + Environment.getExternalStorageDirectory());
        File appDir = new File(Environment.getExternalStorageDirectory(), "Davy");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(filePath);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        String path = file.getAbsolutePath();
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        return path + "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
            myCountDownTimer = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume(); // 必须调用！
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause(); // 必须调用！
    }

    private void handleMapClick(GeoPoint point) {
        double latitude = point.getLatitude();
        double longitude = point.getLongitude();
        mLongitude = decimalFormat.format(longitude);
        mLatitude = decimalFormat.format(latitude);
        mAltitude = decimalFormat1.format(point.getAltitude());
        // 显示经纬度信息
        tvLocation.setText("经度：" + mLongitude + "  纬度" + mLatitude);
//        ToastUtil.showNew(mContext, "Lat: " + mLatitude + "\nLon: " + mLongitude);
        refreshMarkers(point);
    }

    private IMapController mapController;
    private final List<Marker> activeMarkers = new ArrayList<>();

    // 清除所有标记点并添加新标记点
    public void refreshMarkers(GeoPoint newLocations) {
        clearAllMarkers();

        addMarker(newLocations);

        // 如果有新标记，将地图中心移动到第一个标记位置
        mapController.animateTo(newLocations);
    }

    // 添加单个标记点
    private void addMarker(GeoPoint point) {
        Marker marker = new Marker(mapView);
        marker.setPosition(point);
        marker.setIcon(mContext.getResources().getDrawable(R.mipmap.icon_dw));
        marker.setOnMarkerClickListener((marker1, mapView) -> {
            LogUtils.e("TAG", "onMarkerClick");
            return false;
        });
        // 添加到地图和管理列表
        mapView.getOverlays().add(marker);
        activeMarkers.add(marker);

        // 刷新地图
        mapView.invalidate();
    }

    // 清除所有标记点
    private void clearAllMarkers() {
        // 从地图上移除
        List<Overlay> overlays = mapView.getOverlays();
        overlays.removeAll(activeMarkers);

        // 清空管理列表
        activeMarkers.clear();

        // 刷新地图
        mapView.invalidate();
    }
}
